<template>
  <div class="app-container">
  <div class="chart-management">
    <el-input placeholder="请输入图表名字" style="width:200px" v-model="queryChartName" clearable></el-input><el-button icon="el-icon-search" circle @click="handleQueryByChartName()"></el-button>
    <el-row :gutter="20"> <!-- 添加gutter可以设置卡片之间的间隔 -->
      <el-col :span="6" v-for="(chartData, index) in displayedCharts" :key="index"> <!-- 每个卡片占6列，共4列 -->
        <el-card
          :body-style="{ padding: '10px',height:'545px'}"
          shadow="hover"
          class="chart-card"
        >
        <div ref="chartContainer" :id="`chart-${index}`" style="width: 100%; height: 300px;"></div>
        <p>{{ chartData.genResult }}</p>
        <div class="chart-actions"  style="position: absolute;bottom: 10px;margin-left: 130px;">
          <el-button type="primary" icon="el-icon-edit" circle @click="handleEdit(index)"></el-button>
          <el-button type="success" icon="el-icon-message" circle @click="handleSend(index)"></el-button>
          <el-button type="warning" icon="el-icon-star-off" circle ></el-button>
          <el-button type="danger" icon="el-icon-delete" circle @click="handleDelete(index)"></el-button>
        </div>
        </el-card>
     </el-col>
   </el-row>
  </div>
  <el-dialog title="收件地址" :visible.sync="dialogFormVisible" >
  <el-form ref="receiverForm" :model="receiverForm" :rules="receiverRules">
    <el-form-item prop="subject" label="邮箱主题" :label-width="formLabelWidth">
      <el-input   v-model="receiverForm.subject" ></el-input>
    </el-form-item>
    <el-form-item prop="email" label="邮箱地址" :label-width="formLabelWidth">
      <el-input  v-model="receiverForm.email" ></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="dialogFormVisible = false">取 消</el-button>
    <el-button type="primary" @click="realHandleSend()">确 定</el-button>
  </div>
</el-dialog>
  <div class="pagination-text-center">
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="4"
      layout="total, prev, pager, next, jumper"
      :total="totalNum">
    </el-pagination>
  </div>
      
    </div>
</template>

<script>
import * as echarts from 'echarts'
import { mapGetters } from 'vuex'
import { getChartPagination,getUserChartNum,deleteChartById,queryByChartName } from '@/api/chart';
import { sendImageMail } from '@/api/user';
import 'echarts-wordcloud';//词云
import chinaMap from '@/utils/china-main-city-map.json'//地图

export default {
  data() {
const emailReg = /^([a-zA-Z0-9]+[-_]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
const validateEmail = (rule, value, callback) => {
  if (emailReg.test(value)){
    callback()
  }else{
    callback(new Error('邮箱格式不正确'))
  }
}
const validateSubject = (rule, value, callback) => {
  if (value.length===0) {
    callback(new Error('主题Subject不能为空'))
  } else {
    callback()
  }
}
    return {
      list: null,
      listLoading: true,
      displayedCharts:[],
      decoration:null,
      currentPage:1,
      totalNum:10,
      chartInstances: [],//图表的实例
      dialogFormVisible:false, //发送邮件对话框
      curIndex:0,
      receiverForm:{
        subject:"",
        email:"",
      },
      queryChartName:"",
      formLabelWidth: '120px',
      receiverRules: {
      subject: [{ required: true, trigger: 'blur', validator: validateSubject }],
      email: [{ required: true, message: '请填写电子邮箱', trigger: 'change',validator: validateEmail }]
    },
    }
  },  
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  created() {
    getChartPagination({data:{userAccount:this.name,page:1}}).then(response=>{
      this.displayedCharts=response.data
      return this.initCharts()
    })
    getUserChartNum({data:{userAccount:this.name}}).then(response=>{
      this.totalNum=response.data.totalCount
    })
  },
  methods: {
    handleOptionBeforeSet(param){//一些额外处理，比如JSON中的函数
      if(param.chartType=="词云"){//处理下颜色
          this.decoration.series[0].textStyle.color=function() {
            var r = Math.floor(Math.random() * 256);
            var g = Math.floor(Math.random() * 256);
            var b = Math.floor(Math.random() * 256);
            return 'rgb(' + r + ',' + g + ',' + b + ')';
        };
        }
        else if(param.chartType=="地图"){
          echarts.registerMap('china',chinaMap)
        } else if(param.chartType=="关系图"){//标签转换
          this.decoration.legend[0].data=this.decoration.series[0].categories.map(function (a) {
          return a.name;
        })
        }
    },
    initCharts() {
      this.displayedCharts.forEach((chartData, index) => {
        this.renderChart(chartData, index);
      });
    },
    async renderChart(chartData, index) {
      await this.$nextTick(); // 确保DOM已更新
      const chartDom = document.getElementById(`chart-${index}`);
      this.chartInstances[index]=echarts.init(chartDom)
      let rawData=chartData.chartData
      let cleanedData = rawData.replace(/^\s*\n*\"|\"\n*\s*$/g, '');
      cleanedData = cleanedData.replace(/\s+/g, ' ');
      this.decoration=JSON.parse(cleanedData)
      this.handleOptionBeforeSet(chartData)
      this.chartInstances[index].setOption(this.decoration)
    },
    //换页
    handleCurrentChange(newPage){
      getChartPagination({data:{userAccount:this.name,page:newPage}}).then(response=>{
      this.displayedCharts=response.data
      console.log(response)
      //如果执行换页，那么要将所有的动态实例进行销毁
      this.chartInstances.forEach(element=>{
        element.dispose()
        element=null
      })
      return this.initCharts()
    })
    },
    //删除
    handleDelete(index){
      this.$confirm('此操作将永久删除该图表, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteChartById({data:{chartId:this.displayedCharts[index].id}}).then(response=>{
          console.log(response)
          //删除图表后，重新加载
          getChartPagination({data:{userAccount:this.name,page:1}}).then(response=>{
         this.displayedCharts=response.data
          console.log(response)
        return this.initCharts()
        })
        getUserChartNum({data:{userAccount:this.name}}).then(response=>{
          this.totalNum=response.data.totalCount
        })
      })
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    //将图像发送到邮箱
    handleSend(index) {
    this.dialogFormVisible=true
    this.curIndex=index
    },
    realHandleSend(){
      if (this.chartInstances[this.curIndex]) {
      var imgData = this.chartInstances[this.curIndex].getDataURL({
      pixelRatio: 2, // 导出图片的像素密度，数值越高清晰度越高，但图片体积也会相应变大
      backgroundColor: '#fff', // 图片背景色
      excludeComponents: ['toolbox'] // 排除不需要导出的部分，比如toolbox工具栏
    });
    
    //等待渲染完毕
    this.$nextTick(()=>{
      this.$refs.receiverForm.validate(valid => {
      if(valid){
        sendImageMail({data:{email:this.receiverForm.email,subject:this.receiverForm.subject,imageData:imgData,analyse:this.displayedCharts[this.curIndex].genResult}}).then(response=>{
          if(response.code==200){
        this.dialogFormVisible=false;
        this.$notify({
          title: '成功',
          message: '发送成功，请注意查收！',
          type: 'success'
        });
        this.receiverForm.email=""
        this.receiverForm.subject=""
      }
      else{
        this.$notify.error({
          title: '错误',
          message: '发送失败，原因是：'+response.msg
        });
      }
        })
      }
      else {
      return false
    }
    })
    })
      

  }
    },
    //按图表名称查找
    handleQueryByChartName(){
      if(this.queryChartName===""){
        this.$message({
          message: '警告哦，图表名称不能为空',
          type: 'warning'
        });
      }else{
        queryByChartName({data:{userAccount:this.name,chartName:this.queryChartName}}).then(response=>{
          if(response.data.length===0){
          this.$message({
          message: '没有该名称的图表',
          type: 'warning'
        });
          }else{
            this.displayedCharts=response.data
            this.initCharts()
            this.$notify({
            title: '成功',
            message: '查找成功',
            type: 'success'
          });
          }
          //console.log(response.data.length)
        })
      }
    },
    handleEdit(index){
      this.$router.push({name:'EditChart',params:{id:this.displayedCharts[index].id}})
    }
  }
}
</script>
<style>
.pagination-text-center {
  text-align: center;
}
</style>